package com.blaze.framework.core.cloud.sentinel;

import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.authority.AuthorityException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import com.alibaba.csp.sentinel.slots.block.flow.FlowException;
import com.alibaba.csp.sentinel.slots.block.flow.param.ParamFlowException;
import com.alibaba.csp.sentinel.slots.system.SystemBlockException;
import com.blaze.framework.core.util.domain.exception.DefaultErrorCode;
import com.blaze.framework.core.util.domain.exception.ErrorCode;

import java.util.Arrays;

/**
 * sentinel 限流异常
 * @author created by Zhou Zongbo on 2025/5/23.
 */
public enum SentinelBlockExceptionCode implements ErrorCode {
    FLOW(FlowException.class, "接口限流了", 100000),
    DEGRADE(DegradeException.class, "服务降级了", 100001),
    PARAM_FLOW(ParamFlowException.class, "热点参数限流", 100002),
    SYSTEM_BLOCK(SystemBlockException.class, "系统规则（负载/...）不满足要求", 100003),
    AUTHORITY(AuthorityException.class, "授权规则不通过", 100004);

    private final Class<? extends BlockException> exceptionClass;
    private final String message;
    private final int code;

    SentinelBlockExceptionCode(Class<? extends BlockException> exceptionClass, String message, int code) {
        this.exceptionClass = exceptionClass;
        this.message = message;
        this.code = code;
    }

    public static ErrorCode of(BlockException e) {
        return Arrays.stream(values())
                .filter(type -> type.exceptionClass.isInstance(e))
                .findFirst()
                .orElse(null);
    }

    @Override
    public int getCode() {
        return code;
    }

    @Override
    public String getMsg() {
        return message;
    }


}
